import logging
from datetime import datetime

from formencode.validators import Int

from clutch.globals import C, G
from clutch.controllers import Controller
from clutch.decorators import expose_api, validate
from clutch.exceptions import ContinueTraversal
import clutch.database as db

from clutch.identity.model import session, metadata
import clutch.identity.model as m

log = logging.getLogger('identity')

class Root(Controller):

    def __init__(self):
        self.user = User()

    @expose_api()
    def create_schema(self):
        m.metadata.drop_all()
        m.metadata.create_all()

class User(Controller):

    @expose_api()
    def index(self, **kw):
        q = m.User.query()
        q = q.filter_by(**kw)
        return list(q)

    @expose_api()
    def create(self, **kw):
        u = m.User(**kw)
        m.session.flush()
        m.session.refresh(u)
        return u

    @expose_api()
    def update(self, **kw):
        id = kw.pop('id')
        email_address = kw.pop('email_address')
        q = m.User.query()
        if id is not None:
            q = q.filter_by(id=id)
        elif email_address is not None:
            q = q.filter_by(email_address=email_address)
        u = q.first()
        for k,v in kw.items():
            setattr(u, k, v)
        return u
        
        
